package cn.sirun.com.fca.account.service;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;

import com.tencent.cloud.iov.kernel.HttpStatusCodeListener;
import com.tencent.cloud.iov.kernel.IovKernel;
import com.tencent.cloud.iov.kernel.constant.CommonConst;
import com.tencent.cloud.iov.kernel.constant.StatusCode;
import com.tencent.cloud.iov.kernel.util.CookieUtils;
import com.tencent.cloud.iov.router.Router;
import com.tencent.cloud.iov.util.DateTimeUtils;
import com.tencent.cloud.iov.util.ResourcesUtils;
import com.tencent.cloud.iov.util.ThreadUtils;
import com.tencent.cloud.iov.util.lifecycle.ActivityStackManager;
import com.tencent.cloud.iov.util.storage.TXCacheManager;
import com.tencent.cloud.iov.util.storage.TXSharedPreferencesUtils;
import com.tencent.cloud.uikit.utils.DialogUtils;
import com.tencent.mars.xlog.Log;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

import cn.sirun.com.fca.account.R;
import cn.sirun.com.fca.account.constant.AccountActivityConst;
import cn.sirun.com.fca.account.constant.AccountCommonConst;
import cn.sirun.com.fca.account.constant.CarConst;
import cn.sirun.com.fca.account.model.login.LoginResponse;

/**
 * 登录管理类
 *
 * @author showxiao
 * @date 2018/6/22
 */
public class LoginManager {

    public static final String PERSONAL_INFO_CACHE_KEY = "personal_info_cache_key";

    private static final String TAG = "LoginManager";

    private static volatile LoginManager sInstance;

    private boolean mIsLoggedIn;

    private boolean mIsLoggingIn;

    private List<LoginStatusListener> mLoginStatusListeners;

    public static LoginManager getInstance() {
        if (sInstance == null) {
            synchronized (LoginManager.class) {
                if (sInstance == null) {
                    sInstance = new LoginManager();
                }
            }
        }
        return sInstance;
    }

    private LoginManager() {
        setUpLoginState();
        mLoginStatusListeners = new CopyOnWriteArrayList<>();
    }

    public void setUpLoginState() {
        mIsLoggedIn = TXSharedPreferencesUtils.getBoolean(CommonConst.LOGIN_STATUS);

        // 添加登录态失效状态码监听
        IovKernel.addHttpStatusCodeListener(new HttpStatusCodeListener() {
            @Override
            public void onHttpStatusCode(int code) {
                if (StatusCodeManager.getInstance().isInvalidCode(code)) {
                    // 登录态失效，注销登录，跳转到登录界面
                    onLoginStatusInvalid();
                }
            }
        });

//        // 添加 IM 用户状态监听
//        TXPushManager.getInstance().addImUserStatusListener(new ImUserStatusListener() {
//            @Override
//            public void onForceOffline() {
//                Log.d(TAG, "handleForceOffline() called");
//                // 互踢下线
//                handleForceOffline();
//            }
//
//            @Override
//            public void onUserSigExpired() {
//                // 登录态失效，注销登录，跳转到登录界面
//                onLoginStatusInvalid();
//            }
//
//            @Override
//            public void onConnectionError(int errorCode) {
//            }
//        });
//
//        if (mIsLoggedIn) {
//            TXPushManager.getInstance().autoLogin();
//        }
    }

    public boolean isLogin() {
        return mIsLoggedIn;
    }

    public void handleLoginSuccess(LoginResponse response) {
        setLogin(true);
        saveIMLoginInfo(response);
//        TXPushManager.getInstance().autoLogin();
    }

    /**
     * 添加登录态监听
     *
     * @param listener
     */
    public void addLoginStatusListener(LoginStatusListener listener) {
        if (!mLoginStatusListeners.contains(listener)) {
            mLoginStatusListeners.add(listener);
        }
    }

    /**
     * 移除登录态监听
     *
     * @param listener
     */
    public void removeLoginStatusListener(LoginStatusListener listener) {
        if (mLoginStatusListeners.contains(listener)) {
            mLoginStatusListeners.remove(listener);
        }
    }

    /**
     * Lite IM 互踢，导致强制下线
     */
    public void handleForceOffline() {
//        String notice = ResourcesUtils.getString(R.string.force_offline_notice);
//        showForceOfflineDialog(String.format(notice, DateTimeUtils.getCurDateTime()));
    }

    /**
     * 登录态失效，跳转到登录界面
     */
    public void onLoginStatusInvalid() {
        setLogin(false);
        for (LoginStatusListener loginStatusListener : mLoginStatusListeners) {
            loginStatusListener.onLoginStatusInvalid();
        }

        showLoginStatusInvalidDialog(ResourcesUtils.getString(R.string.login_state_expired));
    }

    public void updatePhoneInfo(String nation, String phone) {
        String phoneInfo = nation + AccountCommonConst.NATION_PHONE_SPLITTER + phone;
        TXSharedPreferencesUtils.setValue(AccountCommonConst.KEY_USER_PHONE_INFO, phoneInfo);
    }

    public void handleLoginResult() {
        String oldUserId = TXSharedPreferencesUtils.getValue(
                AccountCommonConst.CURRENT_USER_ID_KEY);
        String newUserId = CookieUtils.getUserIdValue();
        if (!TextUtils.isEmpty(oldUserId) && !oldUserId.equalsIgnoreCase(newUserId)) {
            TXCacheManager.getInstance().clear();
            for (LoginStatusListener loginStatusListener : mLoginStatusListeners) {
                loginStatusListener.onAccountChanged();
            }
        }
        TXSharedPreferencesUtils.setValue(AccountCommonConst.CURRENT_USER_ID_KEY, newUserId);
    }

    /**
     * 退出登录
     */
    public void logout() {
        setLogin(false);
        CookieUtils.clear();
        TXSharedPreferencesUtils.remove(LoginManager.PERSONAL_INFO_CACHE_KEY);
        TXSharedPreferencesUtils.remove(CarConst.SpKey.CAR_ACTIVATE_INFO);
        TXSharedPreferencesUtils.remove(CarConst.SpKey.CUR_CAR_INFO);
        ThreadUtils.executeOnUiThread(new Runnable() {
            @Override
            public void run() {
                // FIXME: 2018/10/17 @showxiao 通过回调通知上层执行账号登出处理
//                CarActivateInfoManager.clearLocalCarInfo();

                if (!mIsLoggedIn) {
                    for (LoginStatusListener loginStatusListener : mLoginStatusListeners) {
                        loginStatusListener.onLoggedOut();
                    }

                    startLoginActivity();
                }

            }
        });
    }

    /**
     * 清理账户信息
     */
    public void clearAccountInfo() {
        setLogin(false);
        CookieUtils.clear();
        for (LoginStatusListener loginStatusListener : mLoginStatusListeners) {
            loginStatusListener.onLoggedOut();
        }
    }

    private void startLoginActivity() {
        Context context = ActivityStackManager.getInstance().getTopActivity();
        if (context == null) {
            context = AccountServices.getContext();
            if (context == null) {
                return;
            }
        }

        Intent intent = Router.fromPath(AccountActivityConst.Path.LOGIN);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        context.startActivity(intent);

        ActivityStackManager.getInstance().clearStack();

    }

    /**
     * 重新登录
     */
    public void showLoginStatusInvalidDialog(final String notice) {
//        ThreadUtils.executeOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                synchronized (LoginManager.class) {
//                    if (mIsLoggingIn) {
//                        return;
//                    }
//
//                    final Activity activity = ActivityStackManager.getInstance().getTopActivity();
//
//                    if (!mIsLoggingIn && !isLogin() && activity != null
//                            && !activity.isFinishing()) {
//                        mIsLoggingIn = true;
//                        DialogUtils.showDialog(activity, R.string.dialog_title_error_message,
//                                notice, ResourcesUtils.getString(R.string.dialog_btn_title_exit),
//                                ResourcesUtils.getString(R.string.btn_title_login),
//                                new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        dialog.dismiss();
//                                        mIsLoggingIn = false;
//                                        clearAccountInfo();
//                                        ActivityStackManager.getInstance().clearStack();
//                                    }
//                                },
//                                new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        dialog.dismiss();
//                                        startLoginActivity();
//                                        mIsLoggingIn = false;
//                                    }
//                                });
//                    }
//                }
//            }
//        });
    }

    public void showForceOfflineDialog(final String notice) {
//        ThreadUtils.executeOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                synchronized (LoginManager.class) {
//                    final Activity activity = ActivityStackManager.getInstance().getTopActivity();
//                    if (activity != null && !activity.isFinishing()) {
//                        DialogUtils.showDialog(activity, R.string.dialog_title_force_offline,
//                                notice, ResourcesUtils.getString(R.string.dialog_btn_title_logout),
//                                ResourcesUtils.getString(R.string.dialog_btn_re_login),
//                                new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        dialog.dismiss();
//                                        clearAccountInfo();
//                                        startLoginActivity();
//                                    }
//                                },
//                                new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        dialog.dismiss();
//                                        TXPushManager.getInstance().setReLoginListener(new TXPushStatusListener() {
//                                            @Override
//                                            public void onConnectCallback(int code, String
//                                                    message) {
//                                                if (StatusCode.SUCCESS == code) {
//                                                    DialogUtils.showToast(activity,
//                                                            R.string.lite_im_login_success);
//                                                } else {
//                                                    DialogUtils.showToast(activity,
//                                                            R.string.lite_im_login_failed);
//                                                }
//                                                TXPushManager.getInstance().setReLoginListener
//                                                        (null);
//                                            }
//                                        });
//                                        TXPushManager.getInstance().autoLogin();
//                                    }
//                                });
//                    }
//                }
//            }
//        });
    }

    private void setLogin(boolean login) {
        Log.d(TAG, "setLogin() called with: login = [" + login + "]");
        mIsLoggedIn = login;
        TXSharedPreferencesUtils.setBoolean(CommonConst.LOGIN_STATUS, login);
//        if (!login) {
//            TXPushManager.getInstance().logout();
//        }
    }

    /**
     * 保存im 登录信息，需持久化
     *
     * @param response
     */
    private void saveIMLoginInfo(LoginResponse response) {
        if (null == response) {
            return;
        }

        Map<String, String> imInfo = new HashMap<>(4);
//        imInfo.put(PushConstants.LiteIm.LITE_IM_IDENTIFIER, response.getIdentifier());
//        imInfo.put(PushConstants.LiteIm.LITE_IM_USER_SIG, response.getUserSig());
//        imInfo.put(PushConstants.LiteIm.LITE_IM_APP_ID, String.valueOf(response.getAppId()));
//        imInfo.put(PushConstants.LiteIm.LITE_IM_ACC_TYPE, String.valueOf(response.getAccType()));
//        TXSharedPreferencesUtils.setMap(PushConstants.LiteIm.LITE_IM_INFO, imInfo);
    }


}
